import openpyxl
import yaml

# 打开Excel文件
workbook = openpyxl.load_workbook('副本电表资产信息（新门诊综合大楼原有）.xlsx')
sheet = workbook.active

# 初始化默认配置
default_device = {
    'type': 'emeter/DTSU6606_645_07',
    'attrPoll': 1800,
    'tsPoll': 60,
    'attr': [{'key': 'loadpower', 'data': 10}],
    'ts': [{'key': 'electricity', 'factor': 1}]
}

# 初始化额外的 ts key
extra_ts_keys = ['ia', 'ib', 'ic', 'pa', 'pb', 'pc']

# 初始化配置文件
config = {'devices': []}
config2 = {'maters':[]}

# 用于跟踪名称的计数器
name_counter = {}

# 遍历Excel行，从第三行开始
for row in sheet.iter_rows(min_row=3, values_only=True):
    id, name, _, _, addr, _, _, _, _, _, _, _, _= row

    if name in name_counter:
        # 如果名称已经存在，增加计数器并添加后缀
        name_counter[name] += 1
        name_with_suffix = f"{name} {name_counter[name]}"
    else:
        # 如果名称是第一次出现，设置计数器为1
        name_counter[name] = 1
        name_with_suffix = name

    device = {
        'addr': "0000" + str(addr),  # 映射到 addr 字段
        'type': 'emeter/DTSU6606_645_07',
        'name': name_with_suffix,  # 使用唯一的名称
        'attr': [{'key': 'loadpower', 'data': 50}],  # 修正attr字段
        'ts': [{'key': 'electricity', 'factor': 1}]  # 修正ts字段
    }

    # mater = {
    #     "name": name_with_suffix,
    #     "from": "newname",
    #     "id": str(id),
    #     "type": "emeter_MFEM",
    #     "coding": coding,
    #     "factor": 1,
    # }

    # 添加额外的 ts key 和 multiplier 值
    # for key in extra_ts_keys:
    #     device['ts'].append({'key': key, 'factor': multiplier})

    config['devices'].append(device)
    # config2['maters'].append(mater)


# 将配置文件写入YAML文件，指定编码为UTF-8
with open('config.yaml', 'w', encoding='utf-8') as yaml_file:
    yaml.dump(config, yaml_file, default_flow_style=False, allow_unicode=True)
# with open('maters.yaml', 'w', encoding='utf-8') as yaml_file:
#     yaml.dump(config2, yaml_file, default_flow_style=False, allow_unicode=True)

print("配置文件已生成为config.yaml")
